/*
 * @Author: your name
 * @Date: 2020-09-07 08:21:54
 * @LastEditTime    : 2021-11-26 16:54:02
 * @LastEditors     : lzg
 * @Description: In User Settings Edit
 * @FilePath        : /config/js/pl.websocket.js
 */
var myWebSocket = null;
function myWebSocket_Connect(ip, port) {
    //已经连接
    if (myWebSocket != null && myWebSocket.connected) {
        alert("You have connected to the server.");
        return;
    }
    try {
        myWebSocket = new WebSocket("ws://" + ip + ":" + port + "/mqtt");
        myWebSocket.ip = ip;
        myWebSocket.port = port;
        myWebSocket.connected = false;//连接状态
        //已连接
        myWebSocket.onopen = function () {
            myWebSocket.connected = true;
            alert("Connect {ip}:{port} success.".format(myWebSocket));
            getUseablePorts();
        };
        //接收到数据
        myWebSocket.onmessage = function (evt) {
            if (evt.data.startsWith('{')) {//是json格式
                try {
                    let jsonObj = JSON.parse(evt.data);
                    if (jsonObj.method && eval(jsonObj.method)) {
                        eval(jsonObj.method)(jsonObj.data);
                    }
                } catch (error) {
                    alert(error+"\r\n"+evt.data);
                }
            } else {
                let colonIndex = evt.data.indexOf(":");
                let method = evt.data.substr(0, colonIndex);
                let data = evt.data.substr(colonIndex + 1);
                eval(method)(data);
                // console.log(evt.data);
                // if(evt.data.startsWith("newLineReceived")){
                //     newLineReceived(evt.data.replace("newLineReceived:",""));
                // }else if(evt.data.startsWith("dataReceived")){
                //     dataReceived(evt.data.replace("dataReceived:",""));
                // }
            }
        };
        //连接断开
        myWebSocket.onclose = function () {
            myWebSocket.connected = false;
            alert("Can not connect " + myWebSocket.ip + ":" + myWebSocket.port);
        };
        //执行方法
        myWebSocket.executeMethod = function (method, data, successMethod, errorMethod) {
            method = method ? method : "help";
            data = data ? data : "";
            let obj = { method: method, data: data, successMethod: successMethod, errorMethod: errorMethod };
            try {
                myWebSocket.send(JSON.stringify(obj));
            } catch (err) {
                console.log(err);
            }
        };
        //窗口关闭
        window.onbeforeunload = function () {
            //alert();
            myWebSocket.close();
        };
    } catch (err) {
        alert(err);
    }
}